package com.peng.leetcode.tree;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

/**
 * ZigzagLevelOrder1
 * 103. 二叉树的锯齿形层序遍历
 * https://leetcode.cn/problems/binary-tree-zigzag-level-order-traversal/
 * <p>
 * Created on 2022/11/27
 *
 * @author lupeng
 */
public class ZigzagLevelOrder1 {

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<>();
        if (root == null) {
            return ans;
        }
        boolean isLeftOrder = true;
        Queue<TreeNode> q = new ArrayDeque<>();
        q.offer(root);
        while (!q.isEmpty()) {
            ArrayDeque<Integer> levelQ = new ArrayDeque<>();
            int size = q.size();
            for (int i = 0; i < size; i++) {
                TreeNode n = q.poll();
                if (isLeftOrder) {
                    levelQ.addLast(n.val);
                } else {
                    levelQ.addFirst(n.val);
                }
                if (n.left != null) {
                    q.offer(n.left);
                }
                if (n.right != null) {
                    q.offer(n.right);
                }
            }
            isLeftOrder = !isLeftOrder;
            ans.add(new ArrayList<>(levelQ));
        }
        return ans;
    }
}
